package com.chengxiaoxiao.libarypartner.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chengxiaoxiao.libarypartner.R;
import com.chengxiaoxiao.libarypartner.domain.UpdateAppInfo;
import com.chengxiaoxiao.libarypartner.utils.ApiAddress;
import com.chengxiaoxiao.libarypartner.utils.ApkInfoUtils;
import com.chengxiaoxiao.libarypartner.utils.ToastUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import static java.lang.System.currentTimeMillis;

public class SplashActivity extends Activity
{

    public Handler handler = new Handler()
    {
        public void handleMessage(android.os.Message msg)
        {
            //跳转到界面
            jumpActivity();
        }

    };


    private RelativeLayout root;
    private TextView textAppName;
    private TextView textAppVersion;
    private ImageView imgIcon;
    private long startTime;
    private TextView textLoad;



    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        root = (RelativeLayout) findViewById(R.id.root);
        textAppName = (TextView) findViewById(R.id.textAppName);
        textAppVersion = (TextView) findViewById(R.id.textVersion);
        imgIcon = (ImageView) findViewById(R.id.imageIcon);
        textLoad = (TextView) findViewById(R.id.textLoad);


        startTime = currentTimeMillis();
        /**
         * 获取应用消息
         */
        getAppInfo();

        /**
         * 检查更新
         */
        checkUpdate();


        //渐变动画
        AlphaAnimation animation = new AlphaAnimation(0.2f, 1);
        animation.setDuration(2000);
        root.startAnimation(animation);

    }

    /**
     * 检查更新
     */
    private void checkUpdate()
    {


        final AsyncHttpClient client = new AsyncHttpClient();
        client.get(ApiAddress.getApiDomain() + "/client/ClientServlet?op=getnewVersion", new AsyncHttpResponseHandler()
        {
            @Override
            public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody)
            {
                UpdateAppInfo info = new UpdateAppInfo();
                String body = new String(responseBody);
                try
                {
                    //versionName:"1.0","versionCode":2,des:"描述",url:"下载地址"
                    JSONObject jsonObj = new JSONObject(body);
                    String versionName = jsonObj.getString("versionName");
                    int versionCode = jsonObj.getInt("versionCode");
                    String url = jsonObj.getString("url");
                    String des = jsonObj.getString("des");

                    info.setDes(des);
                    info.setUrl(url);
                    info.setVersionCode(versionCode);
                    info.setVersionName(versionName);


                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                //显示弹窗
                showUpdateDialog(info);

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
            {
                //LoadDialogUtils.hidden();
                ToastUtils.makeText(getApplication(), "获取新版本失败");
                startJump();

            }
        });


    }

    /**
     * 弹出更新弹窗
     */
    private void showUpdateDialog(final UpdateAppInfo infos)
    {

        final UpdateAppInfo info = infos;

        if (info.getVersionCode() > ApkInfoUtils.getVersionCode(SplashActivity.this))
        {

            AlertDialog.Builder builder = new AlertDialog.Builder(SplashActivity.this);
            builder.setTitle("发现新版本" + info.getVersionName());
            builder.setMessage(info.getDes());

            builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    String path = getExternalCacheDir() + "/libary.apk";

                    ToastUtils.makeText(SplashActivity.this, "后台下载中....");

                    File file = new File(path);
                    if(file.exists())
                    {
                        file.delete();
                    }


                    HttpUtils utils = new HttpUtils();

                    utils.download(ApiAddress.getDomain() + info.getUrl(), path, true, new RequestCallBack<File>()
                    {
                        @Override
                        public void onSuccess(ResponseInfo<File> responseInfo)
                        {
                            textLoad.setVisibility(View.GONE);

                            // 下载成功
                            String p = responseInfo.result.getAbsolutePath();


                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            Uri data;
                            // 判断版本大于等于7.0
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            {
                                // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
                                data = FileProvider.getUriForFile(SplashActivity.this, "com.chengxiaoxiao.fileProvider", responseInfo.result);
                                // 给目标应用一个临时授权
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            } else
                            {
                                data = Uri.fromFile(responseInfo.result);
                            }
                            intent.setDataAndType(data, "application/vnd.android.package-archive");

                            SplashActivity.this.startActivityForResult(intent,0);
                            //
                            //                            // 跳转系统安装页面
                            //                            Intent intent = new Intent();
                            //                            intent.setAction(Intent.ACTION_VIEW);
                            //                            intent.addCategory(Intent.CATEGORY_DEFAULT);
                            //                            intent.setDataAndType(Uri.fromFile(responseInfo.result), "application/vnd.android.package-archive");
                            //                            startActivityForResult(intent, 0);


                        }

                        @Override
                        public void onFailure(HttpException e, String s)
                        {
                            ToastUtils.makeText(SplashActivity.this, s);

                            /**
                             * 跳转到主界面
                             */
                            startJump();
                        }

                        @Override
                        public void onStart()
                        {
                            super.onStart();

                            //开始下载
                            textLoad.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onLoading(long total, long current, boolean isUploading)
                        {
                            long percent =current/total;

                            textLoad.setText("正在下载中..."+percent+"%");

                        }
                    });
                }
            });

            builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    /**
                     * 跳转到主界面
                     */
                    startJump();
                }
            });

            builder.show();

        } else
        {

            /**
             * 跳转到主界面
             */
            startJump();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        /**
         * 跳转到主界面
         */
        startJump();

    }

    /**
     * 获取应用信息
     */
    private void getAppInfo()
    {
        String verName = ApkInfoUtils.getVerName(this);
        String appName = ApkInfoUtils.getAppName(this);


        textAppName.setText(appName);
        textAppVersion.setText(verName);
        imgIcon.setImageBitmap(ApkInfoUtils.getBitmap(this));

    }


    /**
     * 3秒后跳转
     */
    private void startJump()
    {

        new Thread()
        {
            public void run()
            {
                try
                {
                    long current = System.currentTimeMillis();
                    long used = current - startTime;

                    if (used < 3000)
                    {
                        Thread.sleep(3000 - used);
                    }

                } catch (InterruptedException e)
                {

                    e.printStackTrace();
                }

                handler.sendEmptyMessage(0);

            }
        }.start();
    }

    /**
     * 跳转界面
     */
    private void jumpActivity()
    {
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}
